package util

import (
	"bytes"
	"context"
	"github.com/chromedp/chromedp"
	"github.com/gocolly/colly"
	"io/ioutil"
	"log"
	"mp3/entity"
	"strings"
)

func CollyDownload(url string, configEntity entity.DownloadEntity, title string, heads map[string]string) {

	var cl = colly.NewCollector()
	cl.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
	//cl.AllowURLRevisit = true

	cl.OnRequest(func(r *colly.Request) {
		r.Headers.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36")
		if len(heads) > 0 {
			for key := range heads {
				r.Headers.Set(key, heads[key])
			}
		}
	})

	cl.OnError(func(_ *colly.Response, err error) {
		log.Println("Something went wrong:", url, err)
	})

	cl.OnResponse(func(r *colly.Response) {
		reader := bytes.NewReader(r.Body)
		body, _ := ioutil.ReadAll(reader)
		//读取图片内容
		index := strings.LastIndex(url, "/")
		s := url[index+1:]
		err := ioutil.WriteFile("./img/"+s, body, 0755)
		log.Println(url, err)
	})
	cl.Visit(url)

}

func CreateAllocCtx() (context.Context, context.CancelFunc) {
	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("blink-settings", "imagesEnabled=false"),
		chromedp.Flag("no-default-browser-check", false),
		chromedp.Flag("headless", true),
		chromedp.Flag("-headless", true),
		chromedp.Flag("--headless", true),
		chromedp.Flag("no-sandbox", true),
		chromedp.Flag("blink-settings", "imagesEnabled=false"),
		chromedp.Flag("hide-scrollbars", false),
		chromedp.Flag("mute-audio", true),
		chromedp.WindowSize(0, 0),
		chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`),
	}
	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
	//创建chrome窗口
	return chromedp.NewExecAllocator(context.Background(), options...)
}

func DownloadCollyUtil(url string, ctx context.Context, configEntity entity.DownloadEntity, titile string) (bool, string) {
	path := configEntity.FileDirPath + "/" + titile + configEntity.AudioType
	//path := configEntity.FileDirPath + "/" + titile + ".html"
	//var buf []byte

	//if err := chromedp.Run(ctx, fullScreenshot(url, 90, &buf)); err != nil {
	//	log.Println(err)
	//}
	//SleepTime(300)
	//if len(buf)<int(configEntity.MinNum){
	//	return false,path
	//}
	//if err := os.WriteFile(path, buf, 0o644); err != nil {
	//	log.Println(err)
	//}
	//chromedp.Tasks{
	//	chromedp.Navigate(url),
	//
	//	chromedp.(page.SetDownloadBehaviorBehaviorAllow).WithDownloadPath(wd),
	//	chromedp.Click(sect, chromedp.NodeVisible),
	//	chromedp.Sleep(3 * time.Second),
	//}

	return true, path
}

// fullScreenshot takes a screenshot of the entire browser viewport.
//
// Note: chromedp.FullScreenshot overrides the device's emulation settings. Use
// device.Reset to reset the emulation and viewport settings.
func fullScreenshot(urlstr string, quality int, res *[]byte) chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.Navigate(urlstr),
		chromedp.FullScreenshot(res, quality),
	}
}
